package 力扣._00周赛._376周赛.问题3;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

class Solution2 {
    //0，100000000内的回文数
    public static int[] gethui(int min, int max) {
        List<Integer> list = new ArrayList<>();

        // 生成介于min和max之间的所有回文数
        generatePalindromes(min, max, list);

        int[] result = new int[list.size()];
        for (int i = 0; i < list.size(); i++) {
            result[i] = list.get(i);
        }

        return result;
    }

    private static void generatePalindromes(int min, int max, List<Integer> list) {
        for (int len = 1; len <= String.valueOf(max).length(); len++) {
            generatePalindromesWithLength(len, list, min, max);
        }
    }

    private static void generatePalindromesWithLength(int len, List<Integer> list, int min, int max) {
        int upperBound = (int) Math.pow(10, (len + 1) / 2);
        for (int i = 0; i < upperBound; i++) {
            String prefix = String.valueOf(i);
            StringBuilder palindrome = new StringBuilder(prefix);
            if (len % 2 == 0) {
                palindrome.append(new StringBuilder(prefix).reverse());
            } else {
                palindrome.append(new StringBuilder(prefix.substring(0, prefix.length() - 1)).reverse());
            }
            int palindromeNum = Integer.parseInt(palindrome.toString());
            if (palindromeNum >= min && palindromeNum <= max) {
                list.add(palindromeNum);
            }
        }
    }

    static boolean ishuiwen(int num) {
        String s = String.valueOf(num);
        for (int i = 0, j = s.length() - 1; i < j; i++, j--) {
            if (s.charAt(i) != s.charAt(j))
                return false;
        }
        return true;
    }

    public long minimumCost(int[] nums) {
        int m = Integer.MAX_VALUE, M = Integer.MIN_VALUE;
        for (int num : nums) {
            m = Math.min(m,num);
            M = Math.max(M,num);
        }
        m = (int) Math.pow(10, Math.max(1,String.valueOf(m).length()-2));
        M = (int) Math.pow(10, Math.max(9,String.valueOf(M).length()+1));
        int[] hui = gethui(m, M);
        int min = Integer.MAX_VALUE;
        for (int i = 1; i< hui.length; i++) {
            int mid = hui[i];
            int cost = 0;
            for (int j = 0; j < nums.length; j++) {
                cost += Math.abs(nums[j] - mid);
            }
            min = Math.min(cost, mid);
        }
        return min;
    }

    public static void main(String[] args) {
        int[] nums = new int[]{101, 102, 105, 108, 124};
        long l = new Solution2().minimumCost(nums);
        System.out.println(l);
        System.out.println(ishuiwen(11));
    }
}